package com.demo.db.config;

import com.demo.utils.UUIDGenerator;
import com.zaxxer.hikari.HikariDataSource;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.*;
import org.activiti.engine.impl.cfg.StandaloneProcessEngineConfiguration;
import org.activiti.engine.impl.cfg.standalone.StandaloneMybatisTransactionContextFactory;
import org.noear.solon.Solon;
import org.noear.solon.annotation.Bean;
import org.noear.solon.annotation.Configuration;
import org.noear.solon.annotation.Inject;
import org.noear.solon.aspect.AspectUtil;
import org.noear.solon.core.BeanWrap;
import org.noear.solon.extend.mybatis.MybatisAdapter;
import org.noear.solon.extend.mybatis.integration.MybatisAdapterManager;

import javax.sql.DataSource;

@Slf4j
@Configuration
public class DbConfig {
    @Bean(value = "db1", typed = true)
    public DataSource db1(@Inject("${dataSource.db1}") HikariDataSource ds) {
        return ds;
    }


    @Bean("db1")
    public ProcessEngine initActiviti(@Inject("db1") BeanWrap bw) {
        MybatisAdapter adapter = MybatisAdapterManager.get(bw);


        log.info("-----init activiti");

        //activiti配置
        StandaloneProcessEngineConfiguration pec = new StandaloneProcessEngineConfiguration();

        pec.setDataSource(adapter.getConfiguration().getEnvironment().getDataSource());
        //使用与mybatis一样的事务处理器
        pec.setTransactionFactory(adapter.getConfiguration().getEnvironment().getTransactionFactory());
        pec.setTransactionsExternallyManaged(true);
        pec.setTransactionContextFactory(new StandaloneMybatisTransactionContextFactory());

        pec.setDatabaseSchemaUpdate("false");//不更新表结构

        //主键UUID生成
        pec.setIdGenerator(new UUIDGenerator());


        ProcessEngine pe = pec.buildProcessEngine();

        AspectUtil.binding(Solon.context().wrapAndPut(RuntimeService.class, pe.getRuntimeService()));
        AspectUtil.binding(Solon.context().wrapAndPut(TaskService.class, pe.getTaskService()));
        AspectUtil.binding(Solon.context().wrapAndPut(RepositoryService.class, pe.getRepositoryService()));
        AspectUtil.binding(Solon.context().wrapAndPut(HistoryService.class, pe.getHistoryService()));

        return pe;
    }
}